﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.IO;
using System.Xml.Schema;

namespace Matthew
{
    public partial class FrmOrder : Form
    {
        Order order;
        string validationMsg;
        int valErrorCount, valWarningCount;

        public FrmOrder()
        {
            InitializeComponent();
        }

        private void btnBack_Click(object sender, EventArgs e)
        {
            this.Hide();
            AllFormClass.FormMenu.Show();
        }

        private void btnCheck_Click(object sender, EventArgs e)
        {
            order = new Order();

            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                // reset validation variables
                string fileName = openFileDialog.FileName;
                validationMsg = "";
                valErrorCount = 0;
                valWarningCount = 0;

                try
                {
                    if (fileName != "")
                    {
                        // validation against XML schema
                        XmlSchemaSet schemaset = new XmlSchemaSet();
                        schemaset.Add(null, Settings.InvoiceSchemaFileName);

                        XmlReaderSettings settings = new XmlReaderSettings();
                        settings.ValidationType = ValidationType.Schema;
                        settings.Schemas = schemaset;
                        settings.ValidationEventHandler += new ValidationEventHandler(ValidationEventHandler);

                        XmlReader reader = XmlReader.Create(fileName, settings);
                        while (reader.Read()) ;
                    }
                }
                catch (Exception ex)
                {
                    validationMsg = ex.Message;
                }

                if (validationMsg == "")    // indicating XML validation was a success
                {
                    readXML(fileName);
                }
                else
                {
                    MessageBox.Show("The XML document was not properly verified.\nPlease review the following messages below.\n\n" + validationMsg, "Invalid XML order document");

                    lblOrderID.Text = "Order ID: ";
                    btnAccept.Hide();
                    btnDetails.Hide();
                }
            }

            dgvOrder.DataSource = order.OrderDetails;
            dgvOrder.Refresh();
        }

        void ValidationEventHandler(object sender, ValidationEventArgs e)
        {
            if (validationMsg != "")
            {
                validationMsg += "\n";
            }
            switch (e.Severity)
            {
                case XmlSeverityType.Error:
                    validationMsg += "Error [" + valErrorCount + "]:" + e.Message;
                    valErrorCount++;
                    break;
                case XmlSeverityType.Warning:
                    validationMsg += "Warning [" + valWarningCount + "]:" + e.Message;
                    valWarningCount++;
                    break;
            }
        }

        void readXML(string XMLFileName)
        {
            XmlDocument doc = new XmlDocument();

            // DOM approach
            try
            {
                doc.Load(XMLFileName);

                order.OrderID = doc.GetElementsByTagName("Order").Item(0).Attributes[0].Value;
                order.Date = doc.GetElementsByTagName("Date").Item(0).InnerXml;
                order.BuyerID = doc.GetElementsByTagName("BuyerID").Item(0).InnerXml;
                order.Notes = doc.GetElementsByTagName("Notes").Item(0).InnerXml;
                order.SpecialInstructions = doc.GetElementsByTagName("SpecialInstructions").Item(0).InnerXml;

                XmlNodeList itemsList = doc.GetElementsByTagName("Item");
                foreach (XmlNode node in itemsList)
                {
                    OrderDetail detail = new OrderDetail();

                    if (node.Attributes.Count > 0)
                    {
                        detail.ItemID = node.Attributes[0].Value;
                    }

                    if (node.HasChildNodes)
                    {
                        XmlElement childNode = (XmlElement)node.FirstChild;
                        for (int id = 0; id < node.ChildNodes.Count; id++)
                        {
                            switch (childNode.Name)
                            {
                                case "Quantity":
                                    detail.Quantity = childNode.InnerXml;
                                    break;
                                case "UnitPrice":
                                    detail.UnitPrice = childNode.InnerXml;
                                    break;
                                default:
                                    break;
                            }

                            childNode = (XmlElement)childNode.NextSibling;
                        }
                    }

                    order.OrderDetails.Add(detail);
                }

                lblOrderID.Text = "Order ID: " + order.OrderID;
                btnAccept.Show();
                btnDetails.Show();
            }
            catch (Exception)
            {
                MessageBox.Show("An error has been encountered while reading the XML document.\nPlease verify with the buyer.", "Order failed to process");

                lblOrderID.Text = "Order ID: ";
                btnAccept.Hide();
                btnDetails.Hide();
            }
        }

        private void btnAccept_Click(object sender, EventArgs e)
        {
            acceptOrder();
        }

        public bool acceptOrder()
        {
            DialogResult result = MessageBox.Show("Are you sure you wish to accept this order?", "Accept Order", MessageBoxButtons.YesNo);
            if (result == DialogResult.Yes)
            {
                if (DBManager.AddOrder(order))
                {
                    MessageBox.Show("The order has been stored in the database!", "Order accepted");

                    // resetting values
                    lblOrderID.Text = "Order ID: ";
                    btnAccept.Hide();
                    btnDetails.Hide();
                    order = null;
                    dgvOrder.DataSource = null;
                }
                else
                {
                    MessageBox.Show("The order was not accepted.\nPlease verify that your database connection settings are correct.\nThis could be due to an order with the same ID existing in the database.\n\nIf this is the first time adding, there could be a fault with the order.\nPlease verify with the buyer.", "Duplicate order");
                }
                return true;
            }
            else
            {
                return false;
            }
        }

        private void btnDetails_Click(object sender, EventArgs e)
        {
            AllFormClass.FormOrder2.order = order;
            AllFormClass.FormOrder2.Initalize();

            AllFormClass.FormOrder2.Show();
            this.Hide();
        }
    }
}
